<template>
  <el-dialog
    title="分配角色"
    :visible="showRoleDialog"
    @close="handleCloseDialog"
    @open="handleOpenDialog"
  >
    <el-checkbox-group v-model="checkList" v-loading="loading">
      <el-checkbox v-for="item in rolelist" :key="item.id" :label="item.id">
        {{ item.name }}
      </el-checkbox>
    </el-checkbox-group>
    <template #footer>
      <el-button type="primary" size="small" @click="assignRoles">
        确定
      </el-button>
      <el-button size="small" @click="handleCloseDialog">取消</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { getRoleListApi } from '@/api/setting'
import { getSysUserInfoApi } from '@/api/user'
import { assignRolesApi } from '@/api/employess'
import { Message } from 'element-ui'
export default {
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    },
    // 用户的id 用来查询当前用户的角色信息
    userId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      checkList: [], // 数组，存储提交给后台的选中的角色id
      rolelist: [], //
      loading: false
    }
  },
  created() {},
  methods: {
    handleCloseDialog() {
      this.$emit('update:showRoleDialog', false)
      this.checkList = []
    },
    // 打开弹层时，所触发的方法
    async handleOpenDialog() {
      this.loading = true
      //   等两个接口都请求完了，再关闭loading
      // 1：等待原则：等待所有的promise都完成，才会继续执行
      //   Promise.all([Promise1, Promise1]).then(() => {})
      //   2.async函数，默认就相当于进行了一层promise包裹，async函数的执行结果，本身就是一个promise对象
      Promise.all([this.getRoleList(), this.getEmployeeDetail()]).then(() => {
        this.loading = false
      })
    },
    // 获取角色列表
    async getRoleList() {
      const {
        data: { rows }
      } = await getRoleListApi(1, 999)
      this.rolelist = rows
    },
    // 获取员工详情
    async getEmployeeDetail() {
      const res = await getSysUserInfoApi(this.userId)
      this.checkList = res.data.roleIds
    },
    async assignRoles() {
      await assignRolesApi(this.userId, this.checkList)
      Message.success('分配角色成功')
      this.handleCloseDialog()
    }
  }
}
</script>
